//
//  NSString+Verity.m
//  CheHu_EPT
//
//  Created by Apple on 15/8/24.
//  Copyright (c) 2015年 Durlings. All rights reserved.
//

#import "NSString+Verity.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation NSString (Verity)

/** 手机号码判断 */
- (BOOL)CheckPhoneNumInput {
    NSString *Regex =@"^[1][3-8]+\\d{9}";
    NSPredicate *mobileTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
    return [mobileTest evaluateWithObject:self];
}

/** 正则匹配用户密码8-32位数字和字母的组合 */
- (BOOL)checkPassword
{
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{8,32}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:self];
    return isMatch;
}

/** 验证只能是数字或字母 */
- (BOOL)isNumOrLetter
{
    NSString *pattern = @"^[A-Za-z0-9]+$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:self];
    return isMatch;
}


/** 字母或汉字开头,且只能是字母汉字 */
- (BOOL)VerityContent
{
    NSString *string = @"([\\w]|[\\u4e00-\\u9fa5]|[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？~\\[\\]\\\"\\-\\~\\s·～／])+";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", string];
    BOOL isMatch = [pred evaluateWithObject:self];
    return !isMatch;
}

/** 特殊字符串 */
- (NSString *)encodeURL
{
    NSString *newString = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)));
    if (newString) {
        return newString;
    }
    return @"";
}

// 匹配身份证号码
- (BOOL)validateIdentityCard
{
    NSString * regex = [NSString stringWithFormat:@"^[A-Za-z0-9]{0,%li}$",self.length];
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:self];
    return isMatch;
}



/** 邮箱 */
- (BOOL)validateEmail
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}


/** 昵称 */
- (BOOL) validateNickname
{
    NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{4,15}$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:self];
}


/** 256 */
- (NSString *)sha256
{
    uint8_t digest [CC_SHA256_DIGEST_LENGTH];
    NSData *src = [self dataUsingEncoding:NSUTF8StringEncoding];
    CC_SHA256([src bytes], (CC_LONG)[src length], digest);
    NSMutableString *resultString = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH*2];
    for (int i= 0; i<CC_SHA256_DIGEST_LENGTH; i++) {
        
        [resultString appendFormat:@"%02x",digest[i]];
    }
    return  resultString;
}


/**
 *  得到当前时间
 *
 *  @return yyyyMMddHHmmssSSS
 */
+ (NSString *)getNowDate
{
    NSDate *senddate = [NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setTimeZone:[NSTimeZone localTimeZone]];
    [dateformatter setDateFormat:@"yyyyMMddHHmmssSSS"];
    NSString *locationString = [dateformatter stringFromDate:senddate];
    return locationString;
}

-(void)count{
    
}

+(void)count{
    
}

//1. 整形判断
- (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

/**  判断银行卡号
 * 当你输入信用卡号码的时候，有没有担心输错了而造成损失呢？其实可以不必这么担心，  
 * 因为并不是一个随便的信用卡号码都是合法的，它必须通过Luhn算法来验证通过。 
 该校验的过程：   
 * 1、从卡号最后一位数字开始，逆向将奇数位(1、3、5等等)相加。   
 * 2、从卡号最后一位数字开始，逆向将偶数位数字，先乘以2（如果乘积为两位数，则将其减去9），再求和。   
 * 3、将奇数位总和加上偶数位总和，结果应该可以被10整除。
 */
-(BOOL)isValidCardNumber
{
    NSString *digitsOnly = self;
    if(self.length<13) return NO;
    int sum = 0; int digit = 0; int addend = 0;
    BOOL timesTwo = false;
    for (NSInteger i = digitsOnly.length - 1; i >= 0; i--)
    { digit = [digitsOnly characterAtIndex:i] - '0';
        if (timesTwo) { addend = digit * 2;
            if (addend > 9) { addend -= 9; }
        } else { addend = digit; }
        sum += addend; timesTwo = !timesTwo;
    }
    int modulus = sum % 10;
    return modulus == 0;
}

@end
